package com.bwc.aidemo.paoqian

import android.content.Context
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bwc.aidemo.R

class WeekPagerAdapter(
    private val context: Context,
    private val weeklyDataList: List<List<DailyData>>,
    private val onBarClick: (DailyData) -> Unit
) : RecyclerView.Adapter<WeekPagerAdapter.WeekViewHolder>() {

    inner class WeekViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val container: LinearLayout = itemView.findViewById(R.id.ll_daily_container)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WeekViewHolder {
        val view = LayoutInflater.from(context)
            .inflate(R.layout.item_week_chart, parent, false)
        return WeekViewHolder(view)
    }

    override fun onBindViewHolder(holder: WeekViewHolder, position: Int) {
        val weekData = weeklyDataList[position]
        holder.container.removeAllViews() // 清空容器

        // 添加7天的数据
        weekData.forEach { dailyData ->
            val barView = LayoutInflater.from(context)
                .inflate(R.layout.item_daily_bar, holder.container, false)

            // 绑定基础信息
            barView.findViewById<TextView>(R.id.tv_day).text = dailyData.day

            // 处理训练/休息状态
            val training = dailyData.training
            if (training == null) {
                // 休息状态
                setupRestBar(barView)
            } else {
                // 训练状态
                setupTrainingBar(barView, training)
            }

            // 点击事件
            barView.findViewById<View>(R.id.v_bar).setOnClickListener {
                onBarClick(dailyData)
            }

            holder.container.addView(barView)
        }
    }

    // 设置休息状态的柱子
    private fun setupRestBar(barView: View) {
        barView.findViewById<View>(R.id.v_bar).apply {
            layoutParams.height = dpToPx(50) // 固定矮高度
            setBackgroundResource(R.drawable.shape_bar_rest)
        }
        barView.findViewById<TextView>(R.id.tv_distance).visibility = View.GONE
        barView.findViewById<TextView>(R.id.tv_rest).visibility = View.VISIBLE
    }

    // 设置训练状态的柱子
    private fun setupTrainingBar(barView: View, training: TrainingDetail) {
        // 计算柱子高度（根据距离）
        val height = training.distance?.let { calculateBarHeight(it) }
        barView.findViewById<View>(R.id.v_bar).apply {
            if (height != null) {
                layoutParams.height = height
            }
            // 根据训练类型设置颜色
            setBackgroundResource(
                if (training.type?.contains("轻松") == true) R.drawable.shape_bar_easy
                else R.drawable.shape_bar_interval
            )
        }
        // 显示距离
        barView.findViewById<TextView>(R.id.tv_distance).text = training.distance
        barView.findViewById<TextView>(R.id.tv_distance).visibility = View.VISIBLE
        barView.findViewById<TextView>(R.id.tv_rest).visibility = View.GONE
    }

    // 根据距离计算柱子高度（dp）
    private fun calculateBarHeight(distance: String): Int {
        return try {
            when {
                distance.contains("km") -> {
                    // 1km = 100dp，限制在80-300dp之间
                    val km = distance.replace("km", "").toFloat()
                    (km * 100).toInt().coerceIn(80, 300)
                }
                distance.contains("m") -> {
                    // 400m×3 取400m计算，10m=1dp
                    val m = distance.split("×").first().replace("m", "").toInt()
                    (m / 10).toInt().coerceIn(50, 200)
                }
                else -> dpToPx(100) // 默认高度
            }
        } catch (e: Exception) {
            dpToPx(100)
        }
    }

    // dp转px工具方法
    private fun dpToPx(dp: Int): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dp.toFloat(),
            context.resources.displayMetrics
        ).toInt()
    }

    override fun getItemCount() = weeklyDataList.size
}